package cn.hg.solon.youcan.system.provider;

import cn.hg.solon.youcan.common.exception.ServiceException;
import cn.hg.solon.youcan.easyquery.util.EntityQueryableUtil;
import cn.hg.solon.youcan.system.entity.Dict;
import cn.hg.solon.youcan.system.entity.EqDict;
import cn.hg.solon.youcan.system.entity.proxy.EqDictProxy;
import cn.hg.solon.youcan.system.service.DictService;
import com.easy.query.api.proxy.client.EasyEntityQuery;
import com.easy.query.api.proxy.entity.select.EntityQueryable;
import com.easy.query.core.api.pagination.EasyPageResult;
import com.easy.query.solon.annotation.Db;
import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.bean.copier.CopyOptions;
import org.dromara.hutool.core.convert.ConvertUtil;
import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.text.StrValidator;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.db.Page;
import org.dromara.hutool.db.PageResult;
import org.noear.solon.annotation.Component;
import org.noear.solon.data.annotation.Tran;

import java.util.List;
import java.util.Map;

/**
 * @author 胡高
 */
@Component
public class EqDictProvider implements DictService {

    @Db("db1")
    private EasyEntityQuery easyEntityQuery;

    private EntityQueryable<EqDictProxy, EqDict> buildQuery(Map<String, Object> paraMap) {
        String type = (String) paraMap.get("type");
        String status = (String) paraMap.get("status");
        String word = (String) paraMap.get("word");

        EntityQueryable<EqDictProxy, EqDict> entityQueryable = this.easyEntityQuery
                // FROM sys_dict AS t
                .queryable(EqDict.class)
                // WHERE t.`type` = ${type} AND t.`status` = ${status}
                .where(t -> {
                    t.type().eq(StrValidator.isNotBlank(type), type);
                    t.status().eq(StrValidator.isNotBlank(status), status);
                    // AND (t.`name` LIKE '%${word}%' OR t.`type` LIKE '%${word}%')
                    t.or(StrValidator.isNotBlank(word), () -> {
                        t.name().like(word);
                        t.type().like(word);
                    });
                });
        return entityQueryable;
    }

    private EntityQueryable<EqDictProxy, EqDict> buildQuery(Page page, Map<String, Object> paraMap) {
        // ORDER BY ${sortField}
        return EntityQueryableUtil.applyOrderBy(this.buildQuery(paraMap), page);
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DictService#checkUnique(cn.hg.solon.youcan.system.entity.Dict)
     */
    @Override
    public boolean checkUnique(Dict bean) {
        return !this.easyEntityQuery
                // FROM sys_dict AS t
                .queryable(EqDict.class)
                // WHERE t.`type` = ${bean.type}
                .where(t -> {
                    t.type().eq(bean.getType());
                    // t.`value` = ${bean.value}
                    t.name().eq(bean.getName());
                    // t.`id` <> ${bean.id}
                    t.id().ne(ObjUtil.isNotNull(bean.getId()), bean.getId());
                })
                .any();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DictService#delete(java.util.List)
     */
    @Tran
    @Override
    public boolean delete(List<Integer> idList) {
        return this.easyEntityQuery.deletable(EqDict.class).where(t -> t.id().in(idList)).executeRows() > 0L;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DictService#get(java.lang.Integer)
     */
    @Override
    public EqDict get(Integer id) {
        return this.easyEntityQuery.queryable(EqDict.class).whereById(id).firstOrNull();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DictService#getByType(java.lang.String)
     */
    @Override
    public EqDict getByType(String type) {
        return this.easyEntityQuery.queryable(EqDict.class).where(t -> t.type().eq(type)).firstOrNull();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DictService#insert(cn.hg.solon.youcan.system.entity.Dict)
     */
    @Tran
    @Override
    public boolean insert(Dict bean) {
        if (!this.checkUnique(bean)) {
            throw new ServiceException("字典名称已经存在，请更换其它值！");
        }

        EqDict cloneBean = BeanUtil.copyProperties(bean, EqDict.class);

        return this.easyEntityQuery.insertable(cloneBean).executeRows() > 0L;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DictService#listByStatus(java.lang.String)
     */
    @Override
    public List<EqDict> listByStatus(String status) {
        return this.easyEntityQuery
                // FROM sys_dict AS t
                .queryable(EqDict.class)
                // WHERE t.`status` = ${status}
                .where(t -> t.status().eq(status))
                .toList();
    }

    @Override
    public List<EqDict> listBy(Map<String, Object> paraMap) {
        if (ObjUtil.isNull(paraMap)) {
            paraMap = MapUtil.empty();
        }
        return this.buildQuery(paraMap).toList();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DictService#pageBy(int, int, java.util.Map)
     */
    @Override
    public PageResult<EqDict> pageBy(Page page, Map<String, Object> paraMap) {
        EasyPageResult<EqDict> pageList = this.buildQuery(page, paraMap).toPageResult(page.getPageNumber(), page.getPageSize());

        PageResult<EqDict> result = new PageResult<>();
        result.addAll(pageList.getData());
        result.setTotal(ConvertUtil.toInt(pageList.getTotal()));

        return result;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.DictService#update(cn.hg.solon.youcan.system.entity.Dict)
     */
    @Tran
    @Override
    public boolean update(Dict bean) {
        if (!this.checkUnique(bean)) {
            throw new ServiceException("字典名称已经存在，请更换其它值！");
        }

        EqDict cloneBean = this.get(bean.getId());

        BeanUtil.copyProperties(bean, cloneBean, CopyOptions.of().setIgnoreNullValue(true));

        return this.easyEntityQuery.updatable(cloneBean).executeRows() > 0L;
    }

}
